package com.foton.bpc.all.remoting.invoker.impl;

import com.foton.bpc.all.remoting.Client;
import com.foton.bpc.all.remoting.dto.BpcInvacation;
import com.foton.bpc.all.remoting.dto.Response;
import com.foton.bpc.all.remoting.invoker.Invoker;
import com.foton.bpc.all.remoting.netty.channel.BpcChannel;
import com.foton.bpc.all.remoting.netty.handler.BpcClientHandler;
import com.foton.bpc.all.serialzation.Serialzation;
import com.foton.bpc.all.serialzation.json.JsonSerialzation;
import com.foton.bpc.all.util.SpIUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Author RenPu
 * @Date 2023/6/12 17:37
 * @Version 1.0
 * @Description:
 **/
public class BpcClientInvoker  implements Invoker {

    Client client;

    Serialzation serialzation;


    public BpcClientInvoker(Client client, Serialzation serialzation) {
        this.client = client;
        this.serialzation = serialzation;
    }

    @Override
    public Class<?> getInterface() {
        return null;
    }

    @Override
    public Object invoker(BpcInvacation bpcInvacation) throws Exception {

        //1：序列化
        //此处是发起远程调用的实际逻辑
        byte[] requestBody = serialzation.serialzation(bpcInvacation);

        //2:发起请求
        BpcChannel bpcChanel = this.client.getBpcChanel();
        bpcChanel.send(requestBody);


        //3:接收响应
        CompletableFuture completableFuture = BpcClientHandler.withResult(bpcInvacation.getId());
        //阻塞等待进行从furure获取response对象
        Response result = (Response)completableFuture.get(60, TimeUnit.SECONDS);
        if(result.getStatus()==200){
            return result.getContent();
        }else{
            throw new RuntimeException("SERVER ERROR :"+result.getContent());
        }
    }
}
